#include <stdio.h>
#include <stdlib.h>

char *readIn()
{
  int letter, i;
  char *text = malloc(sizeof(char));

  for (i = 0; (letter = getchar()) != EOF; i++)
    {
      text[i] = letter;
      if(text[i]>'A' && text[i]<'Z') //Kleiner Helfer um Buchstaben kleiner zu machen
        {
          text[i] = text[i]+32;
        }
      text = realloc(text, i + 2);
    }
  text[i] = '\0';
  return text;
}

int *letterCount(char *x)
{
  int i;
  int *letter = malloc(26 * sizeof(int));

  //Berechnung der Anzahl der Buchstaben
  for (i = 0; x[i] != '\0'; i++)
    {
      if (x[i] >= 'a' && x[i] <= 'z')
        {
          letter[x[i] - 'a']++;
        }

      if (x[i] >= 'A' && x[i] <= 'Z')
        {
          letter[x[i] - 'A']++;
        }
    }
  return letter;
}

int calcMaxLetter(int *letter)
{
  int i,max_letter;
  for (i = 0, max_letter = letter[0]; i < 26; i++)
    {

      if (max_letter < letter[i + 1])
        {
          max_letter = letter[i + 1];
          continue;
        }

      if ((max_letter > letter[i + 1]) || (max_letter == letter[i + 1]))
        {
          continue;
        }
    }
  printf("Max Letter: %d\n",max_letter);
  return max_letter;
}

int *letterPrint(int *letter)
{
  char alphabet;
  int i;

  for (alphabet = 'a', i = 0; alphabet <= 'z'; alphabet++)
    {
      printf("%c (%d)\n", alphabet, letter[i]);
      i++;
    }

  printf("----\n");
  return 0;
}

char calcKey(int *letter, int max_letter)
  {
    char alphabet, key;
    int i;
    for(alphabet='a', i=0, key='a'; alphabet<='z'; alphabet++)
      {
        if(letter[i]==max_letter)
          {
            key = alphabet;
            printf("%c\n",alphabet);
          }
        i++;
      }
    return key;
  }

char letterDecode(char key, char *text) //modulo
{
  char alphabet = 'e';
  char sec_key, a;
  int i;
 // MODULO UND BEI ANFANG VOM ALPHABTE WEITER FUNZT NET!!
  sec_key = ((alphabet - key)+'z') % 'z';
  printf("SecKey: %d\n\n", sec_key);
  for(i=0;text[i]!='\0'; i++)
    {
          text[i] = (text[i]+sec_key) % 'z';
          printf("%c", text[i]);
    }
  //text[i] = text[i];
  //h(ASCII 104) ist key

  return 0;
}

int main()
{
  int max_letter, key;
  char *full_text = readIn();
  (letterCount(full_text));
  max_letter = calcMaxLetter(letterCount(full_text));
  letterPrint(letterCount(full_text));
  key = calcKey(letterCount(full_text), max_letter);
  letterDecode(key, full_text);
  free(full_text);
  printf("\n");
  return 0;
}
